package core.database;

import jade.util.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class StatementSelect {
	
	private Logger log = Logger.getJADELogger(this.getClass().getName());
	
	private Connection dbCon;
	private String tableName;
	private boolean firstField;
	private boolean firstWhere;
	private String strFields;
	private String strWhereFieldValues;
	private Statement st;
	
	public StatementSelect (Connection dbCon) {
		this.dbCon = dbCon;
		this.tableName=null;
		firstField=true;
		firstWhere=true;
		st= null;
	
	}
	
	
	public void addField( String field){
		if (firstField){
			strFields = field;
			firstField = false;
		} else {
			strFields = strFields + ","+field;
		}
	}
	

	
	public void setTableName ( String tableName){
		this.tableName = tableName;
	}
	
	public void addWhere ( String field, long value){
		if (firstWhere){
			strWhereFieldValues = "where "+field+"="+value+" ";
			firstWhere = false;
		} else {
			strWhereFieldValues = strWhereFieldValues + " and "+field+"="+value+" ";
		}
	}
	
	public void addWhere ( String field, String value){
		if (firstWhere){
			strWhereFieldValues = "where "+field+"='"+value+"' ";
			firstWhere = false;
		} else {
			strWhereFieldValues = strWhereFieldValues + " and "+field+"='"+value+"' ";
		}
	}
	
	public ResultSet executeSelect() throws SQLException{
		ResultSet rs=null;
		if (tableName != null && strFields != null) {
			String query = "select "+strFields +" from "+ tableName+ " " +strWhereFieldValues;
			log.info("Execute select:" + query);
			st = dbCon.createStatement();
			rs = st.executeQuery(query);
		}
		return rs;
	}
	
	public void close() throws SQLException{
		
		if (st != null) st.close();
	}
	
	
}
